﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TrainingsApp.Logic {
    public class WhereHelper {

        public static string ConvertToAndSQL(System.Collections.Specialized.StringDictionary dict) {
            string sql = "(1=1";
            if (dict != null) {
                string tmp = string.Empty;
                foreach (string item in dict.Keys) {

                    if (!string.IsNullOrEmpty(tmp = GetSqlItem(item, dict[item]))) {
                        sql += " and " + tmp;
                    }
                }
            }
            return sql + ")";
        }

        public static string ConvertToAndLikeSQL(System.Collections.Specialized.StringDictionary dict) {
            string sql = "(1=1";
            if (dict != null) {
                string tmp = string.Empty;
                foreach (string item in dict.Keys) {
                    if (!string.IsNullOrEmpty(tmp = GetSqlLikeItem(item, dict[item]))) {
                        sql += " and " + tmp;
                    }
                }
            }
            return sql + ")";
        }

        public static string ConvertToOrSQL(System.Collections.Specialized.StringDictionary dict) {
            string sql = "(";
            if (dict != null) {
                string tmp = string.Empty;
                foreach (string item in dict.Keys) {
                    if (!string.IsNullOrEmpty(tmp = GetSqlItem(item, dict[item]))) {
                        if (sql == "(") {
                            sql += tmp;
                        }
                        else {
                            sql += " or " + tmp;
                        }
                    }
                }
            }
            return sql + ")";
        }

        static string GetSqlItem(string key, string val) {
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(val)) {
                if (val.StartsWith("%") || val.EndsWith("%")) {
                    return GetSqlLikeItem(key, val);
                }
                else {
                    return string.Format("{0}='{1}'", key, val);
                }
            }
            return string.Empty;
        }

        static string GetSqlLikeItem(string key, string val) {
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(val)) {
                return string.Format("{0} like '%{1}%'", key, val);
            }
            return string.Empty;
        }
    }
}
